package com.yxq.mdt.app.modules.main.ui;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.alibaba.fastjson.JSON;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.dinuscxj.progressbar.CircleProgressBar;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.chat.EMClient;
import com.hyphenate.util.NetUtils;
import com.liulishuo.okdownload.DownloadTask;
import com.liulishuo.okdownload.SpeedCalculator;
import com.liulishuo.okdownload.core.breakpoint.BlockInfo;
import com.liulishuo.okdownload.core.breakpoint.BreakpointInfo;
import com.liulishuo.okdownload.core.cause.EndCause;
import com.liulishuo.okdownload.core.listener.DownloadListener4WithSpeed;
import com.liulishuo.okdownload.core.listener.assist.Listener4SpeedAssistExtend;
import com.orhanobut.hawk.Hawk;
import com.tencent.bugly.beta.Beta;
import com.yxq.mdt.app.BuildConfig;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.application.App;
import com.yxq.mdt.app.base.BaseActivity;
import com.yxq.mdt.app.constant.Constant;
import com.yxq.mdt.app.constant.SPKey;
import com.yxq.mdt.app.dialog.CostumerDialog;
import com.yxq.mdt.app.modules.login.ui.LoginActivity;
import com.yxq.mdt.app.modules.main.bean.AppVersion;
import com.yxq.mdt.app.modules.main.bean.NameAndPhoneBean;
import com.yxq.mdt.app.modules.main.model.AppModel;
import com.yxq.mdt.app.modules.main.prestener.AppPresenter;
import com.yxq.mdt.app.modules.main.prestener.IAppContract;
import com.yxq.mdt.app.modules.market.ui.MainMarketFragment;
import com.yxq.mdt.app.modules.personal.bean.AddressBean;
import com.yxq.mdt.app.modules.personal.model.AddressModel;
import com.yxq.mdt.app.modules.personal.ui.fragment.MainPersonalFragment;
import com.yxq.mdt.app.modules.pm.ui.PmHomeFragment;
import com.yxq.mdt.app.modules.socialcontact.ui.fragment.MainSocialContactFragmentCoordinatorLayout;
import com.yxq.mdt.app.net.ApiModel;
import com.yxq.mdt.app.utils.BottomNavigationViewUtils;
import com.yxq.mdt.app.utils.MediaPlayerHelper;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import cn.jzvd.Jzvd;

public class MainActivity extends BaseActivity<AppPresenter> implements IAppContract.View {

    @BindView(R.id.main_navigation)
    public BottomNavigationView navBottom;
    @BindView(R.id.fl_content)
    FrameLayout flContent;
    public List<Fragment> mFragmentList;
    private Fragment mCurrentFragment;
    private int currentPage = 0;
    private long clickTime = 0; //记录第一次点击的时间
    private MainMarketFragment mHomePageFragment;
    //    private MainVideoFragment mMainVideoFragment;
    private PmHomeFragment mPmHomeFragment;
    private MainPersonalFragment mMainPersonalFragment;
    private MainSocialContactFragmentCoordinatorLayout mMainSocialContactFragmentCoordinatorLayout;
    private AMapLocationClient mLocationClient = null;  //声明AMapLocationClient类对象
    private AMapLocationClientOption mLocationOption = null; //声明AMapLocationClientOption对象

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        App.getInstance().addActivity(this);
        getCurrentLocationLatLng();
        initFragment();
        initEvent();
        switchFragment(mHomePageFragment);
        loadAddressList();
        addConnectionListener();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Beta.checkUpgrade(false, true);
            }
        }, 1500);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        int tab = getIntent().getIntExtra("tab", -1);
        selectItem(getItemIdByPosition(tab));
    }

    private void addConnectionListener() {
        EMClient.getInstance().addConnectionListener(new EMConnectionListener() {
            @Override
            public void onConnected() {

            }

            @Override
            public void onDisconnected(int errorCode) {
                if (errorCode == EMError.USER_REMOVED) {
                    // 显示帐号已经被移除
                    //Toast.makeText(MainActivity.this, "帐号已经被移除", Toast.LENGTH_SHORT).show();
                } else if (errorCode == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                    // 显示帐号在其他设备登录
                    new Thread(() -> EMClient.getInstance().logout(true)).start();
                    runOnUiThread(() -> exitDialog());
                } else {
                    if (NetUtils.hasNetwork(MainActivity.this)) {
                        //连接不到聊天服务器
                    } else {
                        //当前网络不可用，请检查网络设置
                    }
                }
            }
        });
    }

    /**
     * 退出确认弹出框
     */
    private void exitDialog() {
        Hawk.delete(SPKey.SP_KEY_USER_MY_INFO);
        Hawk.delete(SPKey.SP_KEY_USER_INFO);
        App.getInstance().exit();
        Intent intent = new Intent(mActivity, LoginActivity.class);
        intent.putExtra("login", "other");
        startActivity(intent);
        finish();
    }

    /**
     * 检查APP版本
     */
    private void checkAppVersion() {
        mPresenter.getSzyVersion();
    }

    /**
     * 请求行政区域地址数据
     */
    private void loadAddressList() {
        String address = Hawk.get("addressList", null);
        if (TextUtils.isEmpty(address)) {
            AddressModel.district(new ApiModel.CommonCallback<List<AddressBean>>() {
                @Override
                public void onSuccess(List<AddressBean> addressBeans) {
                    //缓存区域数据
                    Hawk.put("addressList", JSON.toJSONString(addressBeans));
                }

                @Override
                public void onError(String errMsg) {

                }
            });
        }
    }

    private void initEvent() {

        navBottom.setItemIconTintList(null);
        BottomNavigationViewUtils.disableItemScale(navBottom);
        navBottom.setOnNavigationItemSelectedListener(item -> {

            boolean result = false;
            switch (item.getItemId()) {
                case R.id.nav_item_mall://商城
                    if (currentPage != 0) {
                        currentPage = 0;
                        switchFragment(mHomePageFragment);
                        result = true;
                    } else {
                        refreshCurrentPage(0);
                    }
                    break;
                case R.id.nav_item_pm://一拍即合
                    if (currentPage != 1) {
                        currentPage = 1;
                        switchFragment(mPmHomeFragment);
                        result = true;
                    } else {
                        refreshCurrentPage(1);
                    }
                    break;
                case R.id.nav_item_contact://社区
                    if (currentPage != 2) {
                        switchFragment(mMainSocialContactFragmentCoordinatorLayout);
                        currentPage = 2;
                        result = true;
                    } else {
                        refreshCurrentPage(2);
                    }
                    break;
                case R.id.nav_item_mine://我的
                    if (currentPage != 3) {
                        switchFragment(mMainPersonalFragment);
                        currentPage = 3;
                        result = true;
                    } else {
                        refreshCurrentPage(3);
                    }
                    break;
                default:
            }
            return result;
        });
    }

    /**
     * 选中某一个页面
     *
     * @param itemId itemId
     */
    public void selectItem(int itemId) {
        try {
            navBottom.setSelectedItemId(itemId);
            switch (itemId) {
                case R.id.nav_item_pm://一拍即合
                    if (currentPage != 1) {
                        currentPage = 1;
                        switchFragment(mPmHomeFragment);
                    }
                    break;
                case R.id.nav_item_contact://社区
                    if (currentPage != 2) {
                        switchFragment(mMainSocialContactFragmentCoordinatorLayout);
                        currentPage = 2;
                    }
                    break;
                case R.id.nav_item_mine://我的
                    if (currentPage != 3) {
                        switchFragment(mMainPersonalFragment);
                        currentPage = 3;
                    }
                    break;
                default:
                    //商城
                    if (currentPage != 0) {
                        currentPage = 0;
                        switchFragment(mHomePageFragment);
                    }
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initFragment() {
        mFragmentList = new ArrayList<>();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        mHomePageFragment = new MainMarketFragment();
//        mMainVideoFragment = new MainVideoFragment();
        mMainPersonalFragment = new MainPersonalFragment();
        mMainSocialContactFragmentCoordinatorLayout = new MainSocialContactFragmentCoordinatorLayout();
        mPmHomeFragment = new PmHomeFragment();

        mFragmentList.add(mMainPersonalFragment);
        mFragmentList.add(mHomePageFragment);
//        mFragmentList.add(mMainVideoFragment);
        mFragmentList.add(mMainSocialContactFragmentCoordinatorLayout);
        mFragmentList.add(mPmHomeFragment);

        transaction.add(R.id.fl_content, mHomePageFragment);
//        transaction.add(R.id.fl_content, mMainVideoFragment);
        transaction.add(R.id.fl_content, mMainPersonalFragment);
        transaction.add(R.id.fl_content, mMainSocialContactFragmentCoordinatorLayout);
        transaction.add(R.id.fl_content, mPmHomeFragment);
    }

    /**
     * 显示某个fragment
     *
     * @param to 需要显示的fragment
     */
    private void switchFragment(Fragment to) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (mCurrentFragment != null) {
            if (mCurrentFragment != to) {
                // 先判断是否被add过
                if (to.isAdded()) {
                    // 隐藏当前的fragment，显示下一个
                    transaction.hide(mCurrentFragment).show(to).commitAllowingStateLoss();
                } else {
                    // 隐藏当前的fragment，add下一个到Activity中
                    transaction.hide(mCurrentFragment).add(R.id.fl_content, to).commitAllowingStateLoss();
                }
                mCurrentFragment = to;
            }
        } else {
            if (to != null) {
                // add到Activity中
                transaction.add(R.id.fl_content, to).commitAllowingStateLoss();
                mCurrentFragment = to;
            }
        }
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mPresenter = new AppPresenter(this, new AppModel());
        checkAppVersion();
        //getNameAndPhone();
    }

    private void getNameAndPhone() {
        mPresenter.getNameAndPhone();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (Jzvd.backPress()) {
                return true;
            }
            if (!mPmHomeFragment.goBack()) {
                return true;
            }
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        if ((System.currentTimeMillis() - clickTime) > 2000) {
            ToastUtils.showShort("再按一次退出");
            clickTime = System.currentTimeMillis();
        } else {
            App.getInstance().exit();
            ToastUtils.cancel();
        }
    }

    public int getCurrentPage() {
        return currentPage;
    }


    private int getItemIdByPosition(int position) {
        int result = R.id.nav_item_mall;
        switch (position) {
            case 0:
                result = R.id.nav_item_mall;
                break;
            case 1:
                result = R.id.nav_item_pm;
                break;
            case 2:
                result = R.id.nav_item_contact;
                break;
            case 3:
                result = R.id.nav_item_mine;
                break;
        }

        return result;
    }

    /**
     * 连续点击同一按钮，则刷新Activity包含的Fragment
     *
     * @param position
     */
    private void refreshCurrentPage(int position) {

        switch (position) {
            case 0://商城
                mHomePageFragment.refresh();
                break;
            case 1://一拍即合
//                mPmHomeFragment.refresh();
                break;
            case 2://社区
                mMainSocialContactFragmentCoordinatorLayout.refresh();
                break;
            case 3://我的
                mMainPersonalFragment.initData();
                break;
            default:
        }
    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    /**
     * 初始化定位并设置定位回调监听
     */
    private void getCurrentLocationLatLng() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();

     /* //设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景） 设置了场景就不用配置定位模式等
        option.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
        if(null != locationClient){
            locationClient.setLocationOption(option);
            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
            locationClient.stopLocation();
            locationClient.startLocation();
        }*/
        // 同时使用网络定位和GPS定位,优先返回最高精度的定位结果,以及对应的地址描述信息
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //只会使用网络定位
        /* mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);*/
        //只使用GPS进行定位
        /*mLocationOption.setLocationMode(AMapLocationMode.Device_Sensors);*/
        // 设置为单次定位 默认为false
        mLocationOption.setOnceLocation(true);
        //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。默认连续定位 切最低时间间隔为1000ms
        //设置是否返回地址信息（默认返回地址信息）
        //关闭缓存机制 默认开启 ，在高精度模式和低功耗模式下进行的网络定位结果均会生成本地缓存,不区分单次定位还是连续定位。GPS定位结果不会被缓存。
        /*mLocationOption.setLocationCacheEnable(false);*/
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        if (ContextCompat.checkSelfPermission(mActivity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            //申请定位权限
            ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 10086);
        } else {
            //启动定位
            mLocationClient.startLocation();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (mLocationClient != null) {
            if (ContextCompat.checkSelfPermission(mActivity, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                //启动定位
                mLocationClient.startLocation();
            }
        }
    }

    /**
     * 定位回调监听器
     */
    public AMapLocationListener mLocationListener = amapLocation -> {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                double currentLat = amapLocation.getLatitude();//获取纬度
                double currentLon = amapLocation.getLongitude();//获取经度
                amapLocation.getAddress();
                String city = amapLocation.getCity();

                getDoubleNum(currentLon, currentLat, city);
                amapLocation.getAccuracy();//获取精度信息
                amapLocation.getCity();
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + amapLocation.getErrorCode() + ", errInfo:"
                        + amapLocation.getErrorInfo());
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.onDestroy();//销毁定位客户端。
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mLocationClient != null) {
            mLocationClient.startLocation(); // 启动定位
        }
        checkLogin();
    }

    private void checkLogin() {

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mLocationClient != null) {
            mLocationClient.stopLocation();//停止定位
        }
        Jzvd.goOnPlayOnPause();
        MediaPlayerHelper.realese();
    }

    /**
     * 保留两位小数
     */
    public static void getDoubleNum(double currentLon, double currentLat, String city) {
        BigDecimal lon = new BigDecimal(currentLon);
        double newLon = lon.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
        BigDecimal lat = new BigDecimal(currentLat);
        double newLat = lat.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
        Hawk.put(SPKey.SP_KEY_USER_ADDRESS_MAP_LNG, newLon);
        Hawk.put(SPKey.SP_KEY_USER_ADDRESS_MAP_LAT, newLat);
        Hawk.put(SPKey.SP_KEY_USER_ADDRESS_CITY_NAME, city);
        if (BuildConfig.DEBUG) {
            Log.e("定位", newLon + "");
            Log.e("定位", newLat + "");
            Log.e("定位", city);
        }
    }

    @Override
    public void onLoadSuccess(AppVersion appVersion) {
        if (appVersion.getVersion() > AppUtils.getAppVersionCode()) {
            //升级
            updateAPP(appVersion);
        }
    }

    /**
     * 弹出更新提示
     */
    private void updateAPP(AppVersion appVersion) {
        CostumerDialog dialog = new CostumerDialog.Builder(this, R.style.custom_dialog_no_match)
                .setContentView(R.layout.dialog_update_layout)
                .setCancelable(false)
                .create();
        TextView title = dialog.findViewById(R.id.tv_title);
        CircleProgressBar progressBar = dialog.findViewById(R.id.dialog_progress_bar);
        title.setText("软件更新");

        TextView content = dialog.findViewById(R.id.tv_content);
        content.setText(appVersion.getContent());

        //继续
        TextView sure = dialog.findViewById(R.id.tv_sure);
        sure.setText("升级");
        sure.setOnClickListener(v -> {
            progressBar.setVisibility(View.VISIBLE);
            downLoadApp(appVersion.getDownload_url(), progressBar);
        });

        //取消
        TextView cancel = dialog.findViewById(R.id.tv_cancel);
        cancel.setText("取消");
        cancel.setOnClickListener(v -> {
            dialog.dismiss();
        });
        if (appVersion.getType() == 2) {
            //强制升级
            dialog.findViewById(R.id.dialog_left_layout).setVisibility(View.GONE);
        }
        dialog.show();
    }

    private void downLoadApp(String url, CircleProgressBar progressBar) {

        DownloadTask task = new DownloadTask.Builder(url, Constant.EXTRA_DIR_ROOT, url.substring(url.lastIndexOf("/"), url.length()))
                .setMinIntervalMillisCallbackProcess(10)
                .setPassIfAlreadyCompleted(false)
                .build();
        task.enqueue(new DownloadListener4WithSpeed() {
            @Override
            public void infoReady(@NonNull DownloadTask task, @NonNull BreakpointInfo info, boolean fromBreakpoint, @NonNull Listener4SpeedAssistExtend.Listener4SpeedModel model) {
                progressBar.setMax((int) info.getTotalLength());
            }

            @Override
            public void progressBlock(@NonNull DownloadTask task, int blockIndex, long currentBlockOffset, @NonNull SpeedCalculator blockSpeed) {

            }

            @Override
            public void progress(@NonNull DownloadTask task, long currentOffset, @NonNull SpeedCalculator taskSpeed) {
                progressBar.setProgress((int) currentOffset);
            }

            @Override
            public void blockEnd(@NonNull DownloadTask task, int blockIndex, BlockInfo info, @NonNull SpeedCalculator blockSpeed) {

            }

            @Override
            public void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause, @NonNull SpeedCalculator taskSpeed) {
                AppUtils.installApp(task.getFile());
            }

            @Override
            public void taskStart(@NonNull DownloadTask task) {

            }

            @Override
            public void connectStart(@NonNull DownloadTask task, int blockIndex, @NonNull Map<String, List<String>> requestHeaderFields) {

            }

            @Override
            public void connectEnd(@NonNull DownloadTask task, int blockIndex, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields) {

            }
        });
    }

    @Override
    public void onLoadFailed(String err) {

    }

    @Override
    public void onLoadNameAndPhoneSuccess(NameAndPhoneBean nameAndPhoneBean) {
        if (nameAndPhoneBean != null) {
            Hawk.put(SPKey.SP_KEY_NAME_PHONE_INFO, nameAndPhoneBean);
        }
    }

    @Override
    public void onLoadNameAndPhoneFailed(String err) {

    }
}
